// 年级信息
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--学校数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入学校名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--年级数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="年级名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入年级名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="班级名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入班级名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="queryParams.createDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="date"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="年级序号"
            align="center"
            key="orderNum"
            prop="orderNum"
          />
          <el-table-column
            label="年级名称"
            align="center"
            key="name"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="所属学校"
            align="center"
            key="schoolName"
            prop="schoolName"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
            label="量表状态"
            align="center"
            key="usingStatusDictText"
            prop="usingStatusDictText"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-share"
                @click="handleUpdate(scope.row, '详情')"
                v-hasPermi="['system:user:edit']"
                >详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属学校" prop="schoolId">
              <el-cascader
                :options="deptOptions"
                v-model="form.schoolId"
                @change="handleChange"
                :props="{ checkStrictly: true }"
                clearable
                :show-all-levels="false"
                :disabled="displays"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年级名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入年级名称"
                :disabled="displays"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级排序" prop="orderNum">
              <el-input
                v-model="form.orderNum"
                placeholder="请输入年级排序"
                :disabled="displays"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 添加试题 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="tryAdd"
              :disabled="displays"
              >添加班级</el-button
            >
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="loading"
              :data="form.classAddReqs"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                label="序号"
                align="center"
                key="orderNum"
                prop="orderNum"
                width="80"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.orderNum" :disabled="displays" />
                </template>
              </el-table-column>
              <el-table-column
                label="班级名称"
                align="center"
                key="name"
                prop="name"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入班级名称"
                    :disabled="displays"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column label="班主任" align="center" prop="teacherId">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.teacherId"
                    placeholder="选择班主任"
                    clearable
                    style="width: 230px"
                    :disabled="displays"
                  >
                    <el-option
                      v-for="dict in teacherList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </template>
              </el-table-column> -->
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="dislodge(scope.row)"
                    :disabled="displays"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!displays">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  schoolPage, //获取学校
  teacherPage, //获取教师
  gradeAdd, //添加年级
  gradeDel, //删除年级
  gradeList, //年级列表
  gradePut, //修改年级
  gradeDetails, //年级详情
} from "@/api/information/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  classRequired, //班级必填效验
} from "@/utils/verification";
export default {
  dicts: ["sys_normal_disable", "suitable_object", "yes_no_switch"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 类型选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,

      // 日期范围
      dateRange: [],

      displays: false, //禁止输入
      teacherList: [], //班主任列表
      // 表单参数
      form: {
        schoolId: null,
        orderNum: "",
        name: null,
        classAddReqs: [
          {
            orderNum: "1", //编号
            name: null, //班级
            teacherId: null, //教师
          },
        ], //选择题
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },

      // 表单校验
      rules: {
        name: [
          { required: true, message: "年级名称不能为空", trigger: "blur" },
        ],
        schoolId: [{ required: true, message: "请选择学校", trigger: "blur" }],

        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },

  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询量表列表 */
    getList() {
      this.loading = true;
      gradeList(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询下拉树结构 */
    getDeptTree() {
      schoolPage({ type: 2 }).then((res) => {
        this.deptOptions = res.rows.map((item) => {
          return {
            value: item.id,
            label: item.name,
          };
        });
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.schoolId = data.value;
      this.handleQuery();
    },
    handleChange(value) {
      if (value) {
        this.form.schoolId = value[value.length - 1];
        this.getTeacherList();
      }
    },
    // 获取教师列表
    getTeacherList() {
      teacherPage({ schoolId: this.form.schoolId, ifClassTeacher: 1 }).then(
        (res) => {
          this.teacherList = res.rows.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        }
      );
    },
    // 取消按钮
    // 添加试题
    tryAdd() {
      this.form.classAddReqs.push({
        name: null, //班级
        orderNum: this.form.classAddReqs.length + 1, //编号
        teacherId: null, //教师
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        schoolId: null,
        orderNum: "",
        name: null,
        classAddReqs: [
          {
            name: null, // 题目
            orderNum: "1", //编号
            teacherId: null, //是否必填
          },
        ],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log("查询", this.dateRange);

      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加年级";
      this.displays = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      if (type == "详情") {
        this.title = "年级详情";
        this.displays = true;
      } else {
        this.title = "编辑年级";
        this.displays = false;
      }
      gradeDetails(row.id).then((response) => {
        this.form = response.data;
        this.form.schoolId = response.data.schoolId.toString();
        this.getTeacherList();
        this.form.classAddReqs.forEach((item) => {
          item.teacherId = item.teacherId.toString();
        });
        console.log("row", this.form.classAddReqs);
        this.open = true;
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      console.log("fhua", this.form);

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            if (classRequired(this.form.classAddReqs) !== "") {
              this.$modal.msgError(classRequired(this.form.classAddReqs));
            } else {
              gradePut(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            if (classRequired(this.form.classAddReqs) !== "") {
              this.$modal.msgError(classRequired(this.form.classAddReqs));
            } else {
              gradeAdd(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + userIds + '"的数据项？')
        .then(function () {
          return gradeDel(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },

    // 删除
    dislodge(row) {
      this.form.classAddReqs.splice(
        this.form.classAddReqs.findIndex(
          (item) => item.orderNum === row.orderNum
        ),
        1
      );
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "批量导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
  },
};
</script>
<style scoped lang="scss">
.subject {
  width: 100%;
  margin-top: -30px;
  margin-bottom: 10px;
  font-size: 18px;
  padding-left: 5px;
}
</style>


.labelys {
  width: 100%;
  height: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  div:nth-child(1) {
    width: 10px;
    height: 10px;
    background-color: red;
  }
}
</style>